﻿$(function () {

    //session失效父窗口跳转到登录
    if ((location.pathname.toLowerCase() == '/login' || location.pathname.toLowerCase() == '/') &&
        (parent.location.pathname.toLowerCase() != '/login' && parent.location.pathname.toLowerCase() != '/')) {
        //debugger
        parent.location.href = location.href;
    }

    common.init();

    PluginsInit.init();

})

var StockInOutType = {
    In: 1,  //库存-进库
    Out: 2, //库存-出库
}

var CheckState = {
    Input: 1,   //录入
    Wait: 2,    //待审核
    Pass: 3,    //审核成功
    Fail: 4,    //审核未通过
}

var WarningValue = {
    First: 1,   //一级预警天数
    Second: 5,  //二级预警天数
}

var EndState = {
    NO: 2,  //未结单
    YES: 1,  //已结单
}

//解决：手机浏览时模态框内文本不能获得焦点
$(document).ready(function () {
    if (IsMobile()) {
        console.log('解决：手机浏览时模态框内文本不能获得焦点');
        $('input').click(function () {
            $(this).focus();
        });
    }
})

var Root = "/"; //IIS Express
//var PSIRoot = "/PSI/"; //IIS Express

var common = {
    init: function () {
        //common.initDialogDraggable();
        //common.initDialogHeadHoverCss();
    },
    //初始化模态框可以拖动
    initDialogDraggable: function () {
        var divDialog = $('div[id$="-dialog"]');
        if (divDialog.length > 0) {
            $('div[id$="-dialog"]').draggable();//为模态对话框添加拖拽
        }
        //$('div[id$="-dialog"]').css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
    },
    //初始化模态框modal-header:hover光标样式
    initDialogHeadHoverCss: function () {
        var divDialog = $('div[id$="-dialog"]');
        if (divDialog.length > 0) {
            $('div[id$="-dialog"]').find(".modal-header").hover(function () {
                $(this).css({ cursor: "move" });
            });
        }
    }
}

//初始化fileinput
var FileInput = function () {
    var oFile = new Object();

    //初始化fileinput控件（第一次初始化）
    //ctrlName需要初始化的type="file"控件
    //HiddenCtrlName 文件上传成功后赋值给隐藏文本
    //uploadUrl 上传到后台需要处理的Url
    //fileExts 支持哪些类型文件上传
    //maxFileCount 最多可以上传几个文件
    //showPreview 是否显示预览
    //dropZoneEnabled 是否显示拖拽区域
    oFile.Init = function (ctrlName, HiddenCtrlName, uploadUrl, deleteUrl, fileExts, maxFileCount, showPreview, dropZoneEnabled, callback) {
        var control = $(ctrlName);
        fileExts = fileExts ? fileExts : ["jpg", "jpeg", "gif", "png", "bmp"];
        maxFileCount = isNaN(maxFileCount) ? 1 : maxFileCount;
        showPreview = showPreview == undefined ? false : showPreview;
        dropZoneEnabled = dropZoneEnabled == undefined ? false : dropZoneEnabled;
        //初始化上传控件的样式
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: uploadUrl, //上传的地址
            allowedFileExtensions: fileExts,//接收的文件后缀
            showCaption: true,//是否显示标题
            showClose: false,//显示右上角X关闭
            showRemove: false,//显示移除按钮,跟随文本框的那个
            showUpload: true,//是否显示上传后的按钮
            showBrowse: true,//是否显示上传前的上传按钮
            browseClass: "btn btn-primary", //按钮样式 
            showPreview: showPreview,   //是否显示预览
            dropZoneEnabled: dropZoneEnabled,//是否显示拖拽区域
            //minImageWidth: 50, //图片的最小宽度
            //minImageHeight: 50,//图片的最小高度
            //maxImageWidth: 1000,//图片的最大宽度
            //maxImageHeight: 1000,//图片的最大高度
            maxFileSize: 20000,//单位为kb，如果为0表示不限制文件大小
            //minFileCount: 0,
            maxFileCount: maxFileCount, //表示允许同时上传的最大文件个数
            //initialDelimiter: "*$$*", //默认值：'*$$*' 在initialPreview属性中用于上传多个文件时的分隔符。
            enctype: 'multipart/form-data',
            validateInitialCount: true,
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        });

        //导入文件上传完成之后的事件
        $(ctrlName).on("fileuploaded", function (event, data, previewId, index) {
            if (data.response.SubmitResult) {
                if (data.response.SaveMode == "") {
                    if (typeof (FileReader) === 'undefined') {
                        dialog.warning("抱歉，你的浏览器不支持 FileReader，请使用高版本浏览器操作！");
                    } else {
                        var fileContent = data.response.Content;
                        var fileName = data.response.FileName;
                        var extension = data.response.Extension;
                        if (extension && extension.substr(0, 1) == ".") {
                            extension = extension.substring(1);
                        }
                        $(HiddenCtrlName).val("data:image/" + extension + ";base64," + fileContent);
                        toastr.success(fileName + " 上传成功!");

                        //callback();
                    }
                }
            } else {
                //dialog.warning(data.response.Message);
                toastr.warning(data.response.Message);
            }
        }).on("filepreremove", function (event, previewId, index) {
            console.log('filepreremove');
            //图片上传成功后，点击删除按钮的回调函数
            /*var data = new Object();
            var id = $('#txtId').val();
            if (id && id > 0) {
                data.id = $('#txtId').val();

                dialog.confirm('确认要删除文件吗？', function (result) {
                    if (!result) {
                        return;
                    }
                    $.ajax({
                        type: "post",
                        url: deleteUrl,
                        data: { dto: data },
                        success: function (data) {
                            if (data.SubmitResult) {
                                $(ctrlName).fileinput('refresh');//文件框刷新操作
                                return true;
                            } else {
                                dialog.danger('操作失败！Error Message:' + data.Message);
                                return false;
                            }
                        },
                        error: function () {
                            dialog.danger('操作失败！请重试或者联系管理员');
                            return false;
                        },
                        complete: function () {
                            return false;
                        }
                    });
                });
                return false;
            } else {
                $(ctrlName).fileinput('refresh');//文件框刷新操作
            }*/
        });
    }
    return oFile;
};


var PluginsInit = {
    init: function () {
        PluginsInit.initJqueryToastr();
    },
    initJqueryToastr: function () {
        var messageOpts = {
            "closeButton": false,
            "debug": false,
            "positionClass": "toast-bottom-right",
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        };
        if (typeof (toastr) == undefined) {
            toastr.options = messageOpts;
        }
        /*
        //常规消息提示，默认背景为浅蓝色  
         toastr.info("你有新消息了!");  
        //成功消息提示，默认背景为浅绿色 
         toastr.success("你有新消息了!"); 
        //警告消息提示，默认背景为橘黄色 
         toastr.warning("你有新消息了!"); 
        //错误消息提示，默认背景为浅红色 
         toastr.error("你有新消息了!");  
        //带标题的消息框
         toastr.success("你有新消息了!","消息提示");
        //另一种调用方法
         toastr["info"]("你有新消息了!","消息提示");
        */

        /*
        toast-top-left  顶端左边
        toast-top-right    顶端右边
        toast-top-center  顶端中间
        toast-top-full-width 顶端，宽度铺满整个屏幕
        toast-botton-right  
        toast-bottom-left
        toast-bottom-center
        toast-bottom-full-width
        */

        /*
        onclick，点击消息框自定义事件 
        showDuration: “300”，显示动作时间 
        hideDuration: “1000”，隐藏动作时间 
        timeOut: “2000”，自动关闭超时时间 
        extendedTimeOut: “1000” 
        showEasing: “swing”, 
        hideEasing: “linear”, 
        showMethod: “fadeIn” 显示的方式，和jquery相同 
        hideMethod: “fadeOut” 隐藏的方式，和jquery相同
        */
    }
}

/*
//htmlDOM：最外层的DOM，item：需要循环的数据(k-v)，htmlName：目标html标签，property：目标标签里的属性,prefHtmlName：属性值前缀,setValType：设置value形式
var SetFormValues = function (htmlDOM, item, htmlName, property, prefHtmlName, setValType) {
if (!prefHtmlName) { prefHtmlName = ""; }
    htmlDOM.each(function () {
        for (var key in item) {
            var itemValue = eval('item["' + key + '"]');
            if (!itemValue && itemValue !== 0 && itemValue !== false) {
                itemValue = "";
            } else if (typeof (itemValue) == "number") {

            } else if (itemValue.indexOf("/Date(") != -1) { //datetime
                itemValue = ChangeDateFormat(itemValue, "yyyy-MM-dd");
            } else { //string

            }
            var findHtml = htmlName + "[" + property + "='" + prefHtmlName + key + "']";
            if (setValType == "value") {
                $(this).find(findHtml).val(itemValue);
            } else {
                $(this).find(findHtml).html(itemValue);
            }
        }
    });
}
*/

var SetFormValues = function (formid, data, property, dateFmt, objPrefix) {
    if (dateFmt == undefined || (dateFmt != "yyyy-MM-dd" && dateFmt != "yyyy-MM-dd HH:mm:ss")) {
        dateFmt = "yyyy-MM-dd";//默认格式化时间格式，可以传入yyyy-MM-dd或者yyyy-MM-dd HH:mm:ss
    }
    //var hasObject = null;
    var hasObject = {};
    var _json;
    $(formid).each(function () {
        for (var key in data) {
            var itemValue = eval('data["' + key + '"]');
            if (!itemValue && itemValue !== 0 && itemValue !== false) {
                itemValue = "";
            } else if (typeof (itemValue) == "number") {

            } else if (typeof (itemValue) == "boolean") {

            } else if (typeof (itemValue) == "object") {
                //objPrefix = key;
                //hasObject = itemValue;
                hasObject[key] = itemValue;
                continue;
            } else if (itemValue.indexOf("/Date(") != -1) { //datetime
                itemValue = changeDateFormat(itemValue, dateFmt);
            } else if (isJSON(itemValue) && !objPrefix) { //json
                //debugger
                _json = JSON.parse(itemValue);
                var _find_key = '';
                if (_json.checked == "1" || _json.checked == "0") {
                    _find_key = '[' + property + '="' + key + '_child"]';
                    $('[' + property + '="' + key + '"][data-value="' + _json.checked + '"]').prop('checked', true);
                } else {
                    _find_key = '[' + property + '="' + key + '"]';
                }
                $(_find_key).each(function (_j, _item) {
                    var _it = $(_item);
                    if (_it.attr('type') == 'text') {
                        _it.val(_json.value);
                    } else {
                        if (_json.value.indexOf(_it.data('value')) != -1) {
                            _it.prop('checked', true);
                        }
                    }
                });
                continue;
            } else {    //string

            }
            if (!isNaN(Number(key))) {
                console.log("[" + property + "=" + key + "]属性的值不能为数字类型!");
                continue;
            }

            var findHtml = "[" + property + "='" + key + "']";
            if (objPrefix && objPrefix != '') {
                findHtml = "[" + property + "='" + objPrefix + "." + key + "']";
            }
            var obj = $(this).find(findHtml);
            if (obj.length == 0) {
                continue; //没有找到元素
            }
            var tagName = obj.get(0).tagName.toLowerCase();
            var className = obj.get(0).className;
            if (tagName == "input" || tagName == "textarea") {
                obj.val(itemValue);
            } else if (tagName == "select") {
                if (className.indexOf("selectpicker") != -1) {
                    obj.selectpicker('val', itemValue);
                    obj.selectpicker('refresh');
                } else {
                    obj.val(itemValue);
                }
            } else {
                obj.html(itemValue);
            }
        }
    });

    //加载object对象的属性值
    if (hasObject != null) {
        $.each(hasObject, function (key, obj) {
            SetFormValues(formid, obj, property, undefined, key);
        })
    }
}

var GetFormCheckboxRadio = function (data) {
    //获取checkbox和radio数据,组装成数组!!!!!!
    $('input[type="checkbox"]:checked,input[type="radio"]:checked').each(function (i, item) {
        var obj = $(this);
        var name = obj.prop('name');
        var arr_child = { key: '', checked: '', value: [] };
        if (name == '') {
            return;
        } else if (name != '' && $('[name="' + name + '_child"]').length == 0) {
            $('input[name="' + name + '"]:checked').each(function (idx, child) {
                //arr_child.push($(this).data('value'));
                arr_child.key = name;
                arr_child.checked = 'off';   //没有开关
                arr_child.value.push($(this).data('value'));
            });
        } else {
            //if (obj.attr('lay-filter') == 'switchRadio') {  //lay-filter="switchRadio"
            if (name.indexOf('_child') == -1) {
                arr_child.key = name;
                arr_child.checked = obj.data('value');  //有开关
            }

            //获得对应的子元素
            $('[name="' + name + '_child"]').each(function (idx, child) {
                if ($(this).prop('type').toLowerCase() == 'text') {
                    //arr_child.push($(this).val());
                    arr_child.value.push($(this).val());
                } else if ($(this).is(':checked')) {
                    //arr_child.push($(this).data('value'));
                    arr_child.value.push($(this).data('value'));
                }
            });
        }
        eval('data.field.' + name + '= JSON.stringify(arr_child);');
    });
}


function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }

        } catch (e) {
            //console.log('error：' + str + '!!!' + e);
            return false;
        }
    }
    //console.log('It is not a string!')
}

//转换日期格式(时间戳转换为datetime格式)
var changeDateFormat = function (cellval, fmt) {
    var dateVal = cellval + "";
    if (cellval != null) {
        var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        if (fmt == "yyyy-MM-dd HH:mm:ss") {
            return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
        } else if (fmt == "yyyy-MM-dd") {
            return date.getFullYear() + "-" + month + "-" + currentDate;
        } else if (fmt == "yyyy/MM/dd HH:mm:ss") {
            return date.getFullYear() + "/" + month + "/" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
        } else if (fmt == "yyyy/MM/dd") {
            return date.getFullYear() + "/" + month + "/" + currentDate;
        } else {
            return date.getFullYear() + "-" + month + "-" + currentDate;
        }
    }
}

//全局的ajax访问，处理ajax清求时异常
$(document).ajaxSuccess(function (event, xhr, options) {
    var res = xhr.responseText;
    try {
        if (res.indexOf('先登录') != -1) {
            eval(res);
        }
    } catch (e) {
    }
});

//将表单序列化为JSON对象  
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}
//处理$(form).serializeArray()的多行数据时序列化为list对象
//arr：$(form).serializeArray() ， firsProp：arr第一个属性名称 ， func：处理为对象的方法
//new
var GetFormList = function (arr, tableName, firsProp) {
    var objectList = {};
    objectList[tableName] = [];
    var params;
    for (var i = 0 ; i < arr.length ; i++) {
        if (arr[i].name.indexOf('.') == -1) {
            objectList[arr[i].name] = arr[i].value;
        } else if (arr[i].name.indexOf('.' + firsProp) != -1) {
            params = new Object();
            params[arr[i].name.substring(arr[i].name.indexOf('.' + firsProp) + 1)] = arr[i].value;
            objectList[tableName].push(params);
        } else {
            params[arr[i].name.substring(arr[i].name.indexOf('.') + 1)] = arr[i].value;
        }
    }

    var tmp_count = objectList[tableName].length;
    var new_arr = [];
    //清除空元素
    for (var i = 0; i < tmp_count; i++) {
        var item = objectList[tableName][i];
        var all_null = true;
        //判断所有属性是否都为空
        $.each(item, function (key, val) {
            //console.log(key + ',' + val)
            if (val != '') {
                all_null = false;
            }
        });
        if (!all_null) {
            new_arr.push(item);
        }
    }
    objectList[tableName] = new_arr;
    return objectList;
}
//old
var GetFormList_old = function (arr, tableName, firsProp) {
    var objectList = {};
    objectList[tableName] = [];
    var params;
    for (var i = 0 ; i < arr.length ; i++) {
        if (arr[i].name == firsProp) {
            params = new Object();
            params[arr[i].name] = arr[i].value;
            objectList[tableName].push(params);
        } else {
            params[arr[i].name] = arr[i].value;
        }
    }
    return objectList;
}

var dialog = {
    //1.绿色对号 5.红色不开心 7.黄色感叹号  6.绿色笑脸  2.红色叉号  3.黄色问好  4.灰色锁

    //BootstrapDialog.TYPE_DEFAULT,
    default: function (message, title) {
        title = !title ? "提示" : title;
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.alert(message);
        });
    },
    //BootstrapDialog.TYPE_INFO,
    info: function (message, title) {
        title = !title ? "提示" : title;
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.alert(message);
        });
    },
    //BootstrapDialog.TYPE_PRIMARY,
    primary: function (message, title) {
        title = !title ? "提示" : title;
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.alert(message, { icon: 6 });
        });
    },
    //BootstrapDialog.TYPE_SUCCESS,
    success: function (message, title) {
        title = !title ? "提示" : title;
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.alert(message, { icon: 1 });
        });
    },
    //BootstrapDialog.TYPE_WARNING,
    warning: function (message, title) {
        title = !title ? "提示" : title;
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.alert(message, { icon: 7 });
        });
    },
    //BootstrapDialog.TYPE_DANGER
    danger: function (message, title) {
        title = !title ? "提示" : title;
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.alert(message, { icon: 5 });
        });
    },

    confirm: function (message, callback) {
        //BootstrapDialog.confirm({
        //    title: '提示',
        //    message: message,
        //    type: BootstrapDialog.TYPE_DANGER,
        //    closable: true,
        //    btnOKLabel: '确定',
        //    btnCancelLabel: '取消',
        //    callback: callback
        //});

        layer.confirm(message, {
            offset: '200px',
            cancel: function (index, layero) {
                //console.log('点击X按钮');
                layer.close(index);
            }
        }, function (index) {
            //console.log('点击确定按钮');
            layer.close(index);
            callback();
        }
        , function (index) {
            //console.log('点击取消按钮');
            layer.close(index);
        });

        /*layer.open({
            type: 1
          , title: false //不显示标题栏
          , closeBtn: false
          , area: '300px;'
          , shade: 0.8
          , id: 'lay_confirm' //设定一个id，防止重复弹出
          , btn: ['确定','取消']
          , btnAlign: 'c'
          , moveType: 1 //拖拽模式，0或者1
          , content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">你知道吗？亲！<br>layer ≠ layui<br><br>layer只是作为Layui的一个弹层模块，由于其用户基数较大，所以常常会有人以为layui是layerui<br><br>layer虽然已被 Layui 收编为内置的弹层模块，但仍然会作为一个独立组件全力维护、升级。<br><br>我们此后的征途是星辰大海 ^_^</div>'
          , success: function (layero) {
              var btn = layero.find('.layui-layer-btn');
              btn.find('.layui-layer-btn0').attr({
                  href: 'http://www.layui.com/'
                , target: '_blank'
              });
          }
        });*/
    }
}

//判断是否是手机
var IsMobile = function () {
    var isMobile = {
        Android: function () {
            return navigator.userAgent.match(/Android/i) ? true : false;
        },
        BlackBerry: function () {
            return navigator.userAgent.match(/BlackBerry/i) ? true : false;
        },
        iOS: function () {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
        },
        Windows: function () {
            return navigator.userAgent.match(/IEMobile/i) ? true : false;
        },
        any: function () {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
        }
    };

    return isMobile.any(); //是移动设备
}
